package cn.lanqiao.springbootproject.controller;

import cn.lanqiao.springbootproject.service.ArticleService;
import cn.lanqiao.springbootproject.util.CurrentUserUtil;
import cn.lanqiao.springbootproject.util.Result;
import cn.lanqiao.springbootproject.vo.ArticleVO;
import cn.lanqiao.springbootproject.vo.QueryArticleVO;
import cn.lanqiao.springbootproject.vo.UserRoleVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * (Article)控制层
 *
 * @author david
 * @since 2024-10-11 09:33:01
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    /**
     * 服务对象
     */
    @Autowired
    private ArticleService articleService;

    /**
     * 分页查询
     *
     * @param queryArticleVo
     * @return PageInfo<Article>
     */

    @PostMapping("/query")
    public Result getArticlePage(@RequestBody QueryArticleVO queryArticleVo) {
        PageHelper.startPage(queryArticleVo.getPageNum(), queryArticleVo.getPageSize());
        List<ArticleVO> list = articleService.queryByPage();
        return Result.success(new PageInfo<>(list));
    }

    /**
     * 点赞功能
     *
     * @param type      0： 点赞 1：取消点赞
     * @param articleId
     * @return
     */
    @GetMapping("/like/{type}/{articleId}")
    public Result changeLikeCount(@PathVariable int type, @PathVariable int articleId) {
        try {
            int userId = ((UserRoleVO) CurrentUserUtil.get()).getUserId();
            if (type == 0) {
                articleService.likeArticle(userId, articleId);
            } else {
                articleService.unlikeArticle(userId, articleId);
            }
        } catch (RuntimeException e) {
            return Result.fail(620, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }
}
